import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
// import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';

class ShareController extends GetxController {
  final String userName = "嘶哩嘶哩";
  final String qrInfoText = "分享得积分";
  final String qrSubText = "登录获取专属邀请码";
  final String linkToCopy = "https://example.com/invite?code=12345";
  final String avatarAsset = "assets/images/head.png";
  final String qrCodeAsset = "assets/images/qrcode.png";
  final String backgroundAsset = "assets/images/top.png";

  final String wechatIconAsset = "assets/images/share.png";
  final String saveIconAsset = "assets/images/save.png";
  final String copyIconAsset = "assets/images/copy.png";

  final ScreenshotController screenshotController = ScreenshotController();

  Future<Uint8List?> captureShareCard() async {
    try {
      final Uint8List? imageBytes = await screenshotController.capture();
      return imageBytes;
    } catch (e) {
      Get.snackbar(
        "Error",
        "Failed to capture screenshot: $e",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return null;
    }
  }

  Future<void> shareImage() async {
    final imageBytes = await captureShareCard();
    if (imageBytes == null) return;

    try {
      final tempDir = await getTemporaryDirectory();
      final file = await File('${tempDir.path}/share_card.png').writeAsBytes(imageBytes);

      await Share.shareXFiles(
        [XFile(file.path)],
        text: 'Check out this invite!',
      );
      Get.snackbar(
        "Sharing",
        "Image prepared for sharing.",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        "Error",
        "Failed to share image: $e",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  Future<void> saveToGallery() async {
    final imageBytes = await captureShareCard();
    if (imageBytes == null) return;

    try {
      // final result = await ImageGallerySaver.saveImage(
      //   imageBytes,
      //   quality: 90,
      //   name: "share_invite_${DateTime.now().millisecondsSinceEpoch}",
      // );

      // if (result != null && result['isSuccess'] == true) {
      //   Get.snackbar(
      //     "Success",
      //     "Image saved to gallery!",
      //     snackPosition: SnackPosition.BOTTOM,
      //     backgroundColor: Colors.green,
      //     colorText: Colors.white,
      //   );
      // } else {
      //   throw Exception(result['errorMessage'] ?? 'Unknown error saving image');
      // }
    } catch (e) {
      print("Error saving image: $e");
      String errorMessage = "Failed to save image.";
      if (e.toString().toLowerCase().contains('permission')) {
        errorMessage = "Permission denied. Please allow storage access.";
      } else if (e is PlatformException) {
        errorMessage = "Failed to save image: ${e.message}";
      } else {
        errorMessage = "Failed to save image: $e";
      }

      Get.snackbar(
        "Error",
        errorMessage,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  Future<void> copyLink() async {
    try {
      await Clipboard.setData(ClipboardData(text: linkToCopy));
      Get.snackbar(
        "Success",
        "Link copied to clipboard!",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        "Error",
        "Failed to copy link: $e",
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }
}
